import Debounce from "lodash.debounce";

const store = [];

function getFromStore(key) {
  let index = store.indexOf(key);
  if (index > -1) {
    return store[index]
  }
  return null;
}

function deleteFromStore(key) {
  let index = store.indexOf(key);
  if (index > -1) {
    store.splice(index,1)
  }
}


// 侧边栏toggle事件会有延迟,所以重绘也需要500ms延迟
export const addResizeHook = (key, func, invokeAtOnce = true, time = 500) => {

  let listener=func;
  if (time >=0) {
    listener = Debounce(() => {
      func()
    }, time);
  }

  let list = deleteFromStore(key);
  if (!list) {
    list = [];
    store.push(list)
  }
  list.push(listener);

  if (invokeAtOnce) {
    listener();
  }
  window.addEventListener(
    'resize',
    listener
  );
};

export const removeHook = key => {
  const listeners = getFromStore(key);
  if (listeners) {
    for (const listener of listeners) {
      window.removeEventListener('resize', listener);
    }
  }
  deleteFromStore(key)
};

export const eventTrigger = () => {
  window.dispatchEvent(new Event('resize'));
};
